package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"homework11/cache"
	"homework11/models"
	"strconv"
	"time"
)

func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	data := models.Article{

		Title:   title,
		Content: content,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	redis_key := "add_article_" + strconv.Itoa(int(data.ID))
	var article models.Article
	models.DB.Where("id=?", data.ID).First(&article)
	jsonData, _ := json.Marshal(&article)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func Del(c *gin.Context) {
	id := c.Query("id")
	err := models.DB.Where("id=?", id).Delete(&models.Article{})
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "删除失败",
		})
		return
	}
	redis_key := "article_del"
	cache.Rdb.Del(cache.Ctx, redis_key)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return

}
func Detail(c *gin.Context) {
	var article models.Article
	id := c.Query("id")
	redis_key := "article_detail"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Where("id=?", id).First(&models.Article{})
		jsonData, _ := json.Marshal(&article)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &article)
	}
	models.DB.Where("id=?", id).First(&models.Article{})
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"list": article,
	})
	return
}
func List(c *gin.Context) {
	var article []models.Article
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "2"))
	offset := (page - 1) * pageSize
	redis_key := "article_list" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Offset(offset).Limit(pageSize).Find(&article)
		jsonData, _ := json.Marshal(&article)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &article)
	}
	var total int64
	models.DB.Model(&article).Count(&total)

	models.DB.Offset(offset).Limit(pageSize).Find(&article)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"list":  article,
		"total": total,
	})
	return
}
